package handel

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"video/inits"
	rep2 "video/internal/rep"
	req2 "video/internal/req"
	"video/model"
	"video/pkg"
)

func Login(c *gin.Context) {
	var req req2.Login
	err := c.ShouldBind(&req)
	if err != nil {
		return
	}

	var user model.User
	inits.DB.Debug().Where("name = ?", req.Name).Find(&user)
	userId, _ := strconv.Atoi(strconv.Itoa(int(user.ID)))
	handler, err := pkg.TokenHandler(userId)
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": handler,
	})
}
func VideoAdd(c *gin.Context) {
	var req req2.VideoAdd
	c.ShouldBind(&req)
	var video = model.Video{
		Title:  req.Title,
		Image:  req.Image,
		Url:    req.Url,
		Status: req.Status,
		UserId: req.UserId,
		Label:  req.Label,
	}
	inits.DB.Debug().Create(&video)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": video.ID,
	})
}
func VideoList(c *gin.Context) {
	var req req2.VideoList
	c.ShouldBind(&req)
	var video []model.Video
	offset := (req.Page - 1) * req.Size
	tx := inits.DB.Debug().Offset(offset).Limit(req.Size)
	if req.Title != "" {
		tx.Where("title like ?", "%"+req.Title+"%")
	}
	if req.Status != "" {
		tx.Where("status like ?", "%"+req.Status+"%")
	}
	if req.Label != "" {
		tx.Where("label like ?", "%"+req.Label+"%")
	}
	if req.UserId != 0 {
		tx.Where("user_id = ?", req.UserId)
	}
	tx.Find(&video)
	var b []*rep2.VideoLists
	for _, c := range video {
		list := rep2.VideoLists{
			Title:  c.Title,
			Image:  c.Image,
			Url:    c.Url,
			Status: c.Status,
			UserId: c.UserId,
			Label:  c.Label,
		}
		b = append(b, &list)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查看成功",
		"data": b,
	})
}
func VideoLiuLan(c *gin.Context) {
	var req req2.VideoFind
	c.ShouldBind(&req)
	var videodata model.VideoDate
	inits.DB.Debug().Where("id = ?", req.VideoId).Find(&videodata)
	videodata.LiuLan = videodata.LiuLan + 1
	inits.DB.Debug().Updates(&videodata)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "浏览成功",
		"data": videodata.LiuLan,
	})
}
